<template>
  <view class="page">
    <!-- 轮播图 -->
    <view class="contain-box">
      <view class="contain-title">轮播图</view>
      <view class="contain-content">
        <cus-swiper-upload ref="SwiperUpload" name="Img" :imgs="fileImgs" :uploadUrl="uploadUrl"></cus-swiper-upload>
      </view>
    </view>

    <u-gap height="24rpx" bgColor="#F7F8FA"></u-gap>
    <view class="contain-box" v-if="!wxCheckType">
      <view class="contain-title">上传视频</view>
      <view class="contain-content">
        <cus-video-upload ref="VideoUpload" name="Img" :imgs="video" :uploadUrl="uploadUrl"></cus-video-upload>
      </view>
    </view>

    <u-gap height="24rpx" bgColor="#F7F8FA" v-if="!wxCheckType"></u-gap>
    <!-- 商品 -->
    <view class="contain-box">
      <view class="contain-title">商品</view>
      <view class="contain-content">
        <u-button color="#E9F0FD" throttleTime="500" :customStyle="{height:'64rpx',fontSize: '28rpx',color:'#276AEE'}"
                  @click="addGoods">绑定商品
        </u-button>
      </view>
    </view>

    <u-gap height="24rpx" bgColor="#F7F8FA"></u-gap>

    <!-- 产品介绍 -->
    <view class="contain-box">
      <view class="contain-title">产品介绍</view>
      <view class="contain-content">
        <cu-editor ref="editor" :url="uploadUrl" :content="richtext"></cu-editor>
      </view>
    </view>

    <view class="submit-box">
      <u-button color="#276AEE" throttleTime="500" :loading="loading" :customStyle="{height:'88rpx',fontSize: '30rpx'}"
                @click="submit">保存
      </u-button>
    </view>

    <!-- 商铺列表显示 -->
    <bind-goods-popup ref="BindGoodsPopup" @select="goodsSelect"></bind-goods-popup>
  </view>
</template>

<script>
import {mapGetters, mapState} from 'vuex'
import baseConfig from '@/config/baseUrl.js'
import cuEditor from '@/components/cu-editor/cu-editor'
import {handleHtmlImage} from '@/components/cu-editor/util'
import BindGoodsPopup from './components/bind-goods-popup.vue'
import cusVideoUpload from "@/components/cus-video-upload/cus-video-upload.vue";

export default {
  components: {cusVideoUpload, cuEditor, BindGoodsPopup},
  data() {
    return {
      uploadUrl: baseConfig.uploadUrl + '/sys/common/upload',
      model: {},
      richtext: '',
      fileImgs: '',
      video: '',
      goodsData: {},

      loading: false,
    }
  },
  computed: {
    ...mapState(['wxCheckType']),
    ...mapGetters(['userInfo'])
  },
  onLoad(option) {
    // console.log(option);
    this.model.id = option.detailId
    this.model.infoId = option.id
    this.model.name = decodeURI(option.name)

    uni.setNavigationBarTitle({
      title: this.model.name
    })

    if (this.model.id) {
      this.getDBDetail()
    }
  },
  methods: {
    async getDBDetail() {
      uni.showLoading({title: '加载中', mask: true})
      let res = await this.$api.getProductDetaiById(this.model.id)
      uni.hideLoading()
      if (res.success) {
        let tResult = res.result || {}
        this.richtext = tResult.perfile || ''
        this.fileImgs = tResult.banner
        this.video = tResult.video
        this.goodsData.defaultProductId = tResult.defaultProductId
        this.goodsData.goodsId = tResult.goodsId
        this.goodsData.goodsPrice = tResult.goodsPrice
      } else {
        uni.showToast({title: res.message || '获取产品详情失败！', icon: 'none'});
      }
    },
    addGoods() {
      this.$refs.BindGoodsPopup.show()
    },
    async goodsSelect(e) {
      const that = this
      let tPlaceId = `正在加载_${Date.now()}`
      this.$refs.editor.insertText(tPlaceId, async res => {
        let tContent = await this.getRichText()
        let tReg = new RegExp(tPlaceId, "g")
        tContent = tContent.replace(tReg, e.html)
        that.$refs.editor.setValue(tContent) //调用子组件方法回显
      })
    },
    getRichText() {
      const that = this
      return new Promise((resolve, reject) => {
        that.$refs.editor.getContents(res => {
          // console.log(res);
          res.html = handleHtmlImage(res.html)
          resolve(res.html)
        })
      })
    },
    async submit() {
      let tContent = await this.getRichText()
      let params = {
        ...this.model,
        banner: this.$refs.SwiperUpload.getUrl(),
        perfile: tContent,
        openId: this.userInfo.openId,
        video: this.$refs.VideoUpload.getUrl(),
        defaultProductId: this.goodsData.defaultProductId,
        goodsId: this.goodsData.goodsId,
        goodsPrice: this.goodsData.goodsPrice,
      }
      console.log('上传参数', params);
      this.loading = true
      let res = {}
      if (params.id) {
        res = await this.$api.editProductDetail(params)
      } else {
        res = await this.$api.addProductDetail(params)
      }
      this.loading = false
      if (res.success) {
        uni.showToast({title: '保存成功！', icon: 'none'});

        let pages = getCurrentPages(); // 获取当前页面栈
        let prePage = pages[pages.length - 2]; // 上一个页面
        prePage.refresh = true // A 页面 init方法 为true

        setTimeout(() => {
          uni.navigateBack()
        }, 1000)
      } else {
        uni.showToast({title: res.message || '保存失败！', icon: 'none'});
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.page {
  padding-bottom: calc(206rpx + constant(safe-area-inset-bottom) + 265px);
  padding-bottom: calc(206rpx + env(safe-area-inset-bottom) + 265px);
}

.contain-box {
  padding: 32rpx;

  .contain-title {
    font-size: 26rpx;
    color: #1D2129;
    line-height: 36rpx;
  }

  .contain-content {
    margin-top: 16rpx;
  }

  ::v-deep .editor-container {
    .fixed-top {
      display: none !important;
    }

    scroll-view {
      height: unset !important;
    }
  }
}

.submit-box {
  position: fixed;
  bottom: constant(safe-area-inset-bottom);
  bottom: env(safe-area-inset-bottom);
  width: 100%;
  padding: 16rpx 48rpx;
  box-sizing: border-box;
}
</style>
